import { createRouter, createWebHistory } from "vue-router"
import { ElMessage } from "element-plus";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      redirect:'/home'
    },
    {
      path: "/home",
      name: "home",
      component: () =>
        import(/* webpackChunkName: "home" */ "../views/MyHome.vue"),
    },
    {
      path: "/login",
      name: "login",
      component: () =>
        import(/* webpackChunkName: "home" */ "../views/MyLogin.vue"),
    },
    {
      path: "/register",
      name: "register",
      component: () =>
        import(/* webpackChunkName: "home" */ "../views/MyRegister.vue"),
    },
    {
      path: "/:pathMatch(.*)", // vue3 使用带有自定义regexp的参数定义
      name: "notFound",
      component: () =>
        import(/* webpackChunkName: "notFound" */ "../views/404.vue"),
    },
  ],
})
// 设置全局前置导航守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (token) {
    next()
  } else {
    if (to.path == '/login') {
      // 只有想访问/login页面, 才能访问
      next()
    } else {
      ElMessage({
        type: 'error',
        message: '请先登录',
        showClose: true,
        duration: 1000
      })
      // 想访问其它的页面, 都会回到/login
      next('/login')
    }
  }
})
export default router
